import pymysql
import logging

logger = logging.getLogger(__name__)
from conf.settings import mysql_info


class MySQLDB:
    __instance = None

    def __new__(cls, *args, **kwargs):
        if not cls.__instance:
            cls.__instance = object.__new__(cls, *args)
        return cls.__instance

        def __init__(self):
            # 建立数据库连接
            self.conn = pymysql.connect(
                host=mysql_info["host"],
                port=mysql_info["port"],
                user=mysql_info["user"],
                password=mysql_info["password"],
                db=mysql_info["db"],
                charset="utf8"
            )
            # 使用cursor方法获取操作游标
            self.cur = self.conn.cursor(cursor=pymysql.cursors.DictCursor)

        def __del__(self):
            try:
                # 关闭游标
                self.cur.close()
                # 关闭连接
                self.conn.close()
            except Exception as ex:
                logger.error(f"出错了：{ex}")

        def query(self, sql, state="all"):
            try:
                self.cur.execute(sql)

                if state == "all":
                    # 查询全部
                    data = self.cur.fetchall()
                else:
                    # 查询单条
                    data = self.cur.fetchone()
                return data
            except Exception as ex:
                logger.error(f"出错了：{ex}")
                raise

        def execute(self, sql):
            try:
                # 增删改
                rows = self.cur.execute(sql)
                # 提交事务
                self.conn.commit()
                return rows
            except Exception as ex:
                logger.error(f"出错了：{ex}")
                self.conn.rollback()
                raise


if __name__ == '__main__':
    pass
